package cgroup

import (
	"bufio"
	"os"
	"strings"
)

// Default 默认CGroup, 从 /proc/self/mountinfo 读取
var Default = OpenDefault()

// OpenDefault 打开默认CGroup, 从 /proc/self/mountinfo 读取
func OpenDefault() (g *CGroup) {
	g = &CGroup{}
	g.gm = make(map[Key]string, 3)
	f, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		g.err = err
		return
	}
	defer func(f *os.File) { _ = f.Close() }(f)
	for scanner, next := bufio.NewScanner(f), true; next; next = scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if len(fields) != 11 {
			continue
		}
		if fields[8] != "cgroup" {
			continue
		}
		names := strings.FieldsFunc(fields[10], func(r rune) bool { return r == ',' })
		for _, name := range names {
			ss := Key(name)
			switch ss {
			case CPU, CPUSet, Memory:
				g.gm[ss] = fields[4]
				if len(g.gm) == 3 {
					return
				}
				break
			}
		}
	}
	return
}
